const http = require('http');
const fs = require('fs');
const url = require('url');




http.createServer((req, res) => {
  let { pathname } = url.parse(req.url)

  fs.stat(`www${pathname}`, (err, stat) => {
    if (err) {
      console.log('not faound');
      res.writeHeader(404);
      res.write('not found');
      res.end()
    } else {

      if (req.headers['if-modified-since']) {
        //判断文件是否修改
        const oDate = new Date(req.headers['if-modified-since'])
        //客户端的时间
        let time_client = Math.floor(oDate.getTime() / 1000)
        //服务端的时间
        let time_server = Math.floor(stat.mtime.getTime() / 1000)

        //判断客户端和服务端 谁的最新
        if (time_server > time_client) { //服务器的文件时间 > 客户端手里版本
          sendFileToClient()
        } else {
          res.writeHeader(304)
          res.write('Not Modifild')
          res.end()
        }
      } else {
        sendFileToClient()
      }
      //发送
      function sendFileToClient() {
        res.setHeader('cache-control', 'no-cache');
        res.setHeader('Last-Modified', stat.mtime.toGMTString());
        let rs = fs.createReadStream(`www${pathname}`);
        //输出
        rs.pipe(res)
        rs.on('error', err => {
          res.writeHeader(404);
          res.write('not found');
          res.end()
        })
      }
    }

  })



}).listen(9804)